package com.gitee.apanlh.util.encode;

/**
 * 	八进制
 * 
 * 	@author Pan
 */
public class OctUtils {
	
	private static final int LONG_BYTES = 8;
	
	private static final String OCT_DIGITS = "01234567";
	
	private OctUtils() {
		super();
	}
	
	public static String toOctalString(long l) {
		StringBuilder sb = new StringBuilder();
		byte[] bytes = toByteArray(l);
		for (int i = 0; i < bytes.length; i++) {
			sb.append(OCT_DIGITS.charAt((bytes[i] & 0xff) >> 3));
			sb.append(OCT_DIGITS.charAt((bytes[i] & 0xff) >> 2));
			sb.append(OCT_DIGITS.charAt((bytes[i] & 0xff) >> 1));
			sb.append(OCT_DIGITS.charAt((bytes[i] & 0xff) >> 0));
		}
		return sb.toString();
	}
	
	public static String toOctalString(Long l) {
		if (l == null) {
			return null;
		}
		return toOctalString(l.longValue());
	}
	
	public static String toOctalString(int i) {
		return toOctalString((long) i);
	}
	
	public static String toOctalString(Integer i) {
		if (i == null) {
			return null;
		}
		return toOctalString((long) i.intValue());
	}
	
	public static String toOctalString(short s) {
		return toOctalString((long) s);
	}
	
	public static String toOctalString(Short s) {
		if (s == null) {
			return null;
		}
		return toOctalString((long) s.shortValue());
	}
	
	public static String toOctalString(byte b) {
		return toOctalString((long) b);
	}
	
	public static String toOctalString(Byte b) {
		if (b == null) {
			return null;
		}
		return toOctalString((long) b.byteValue());
	}
	
	/**
	 * 	该方法将一个 long 类型的数字转换成一个字节数组，每个字节的值表示原来的 long 类型数字的八位二进制数字。
	 *
	 * 	@author	Pan
	 * 	@param 	l	long
	 * 	@return	byte[]
	 */
	private static byte[] toByteArray(long l) {
		byte[] bytes = new byte[LONG_BYTES];
		for (int i = 0; i < LONG_BYTES; i++) {
			bytes[i] = (byte) ((l >> (LONG_BYTES - i - 1) * 8) & 0xff);
		}
		return bytes;
	}
}
